package myserver.core;

import myserver.WebServer;

import java.io.*;

/**
 * 请求解析器
 * @author Leeyn
 *
 */
public class RequestParser {
    private final static int BUFFER_SIZE = 1024;

    /**
     * 解析请求
     * @param inputStream
     * @return Request
     */
    public Request parse(InputStream inputStream) {


        Request request = new Request();
        InputStream is1=null;
        InputStream is2=null;
        if(inputStream!=null){

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer=new byte[8192];
            int len;
            try{
                if((len=inputStream.read(buffer))>-1){
                    baos.write(buffer,0,len);
                }
                baos.flush();
            }catch (Exception ex){
                ex.printStackTrace();
            }

            is1 = new ByteArrayInputStream(baos.toByteArray());
            request.setInput(is1);
            is2 = new ByteArrayInputStream(baos.toByteArray());
        }
        // 读取请求信息
        String requestMessage = readRequestMessage(is2);
        System.out.println(requestMessage);
        // 解析请求方式
        String type = parseType(requestMessage);
        request.setType(type);
        // 解析请求URI
        String uri = parseUri(requestMessage);
        request.setUri(uri);

        //TODO 自己扩展 更多的解析方案
        String[] params=parse_params(parse_qsparams(uri),parse_formdata(requestMessage));
        request.setParams(params);

        String headers=parse_header(requestMessage);
        request.setHeaders(headers);

        String raws=parse_raw(requestMessage);
        request.setRaws(raws);

        byte[] binary=parse_binary(requestMessage);
        request.setBinary(binary);

        int index=parse_index(requestMessage);
        request.setIndex(index);
        //request.setInput(inputStream);


        return request;
    }


    /**
     * 读取请求信息
     * @param input
     * @return
     */
    private String readRequestMessage(InputStream input){
        StringBuffer requestMessage = new StringBuffer();
//        try{
//        BufferedReader br=new BufferedReader(new InputStreamReader(input,"UTF-8"),BUFFER_SIZE);
//        String str;
//            while((str=br.readLine())!=null){
//                System.out.println(str);
//                requestMessage.append(str);
//            }
//        }catch (Exception ex){
//            ex.printStackTrace();
//        }
//        int readLength = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
//        String str = null;
        try {
            input.read(buffer);
            requestMessage.append(new String(buffer,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
//            readLength = -1;
        }

//        for(int i = 0; i < readLength; i++) {
//            requestMessage.append((char)buffer[i]);
//        }
        return requestMessage.toString();
    }

    /**
     * 解析请求方式
     * @param requestString
     * @return
     */
    private String parseType(String requestString) {
        int index = 0;
        index = requestString.indexOf(' ');
        if (index != -1) {
            return requestString.substring(0, index);
        }
        return null;
    }

    /**
     * 解析请求URI
     * @param requestString
     * @return
     */
    private String parseUri(String requestString) {


        int index1, index2;
        index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
            if (index2 > index1)
                try {
                    return java.net.URLDecoder.decode(requestString.substring(index1 + 1, index2),"UTF-8");
                }catch (Exception ex){
                    ex.printStackTrace();
                }

        }
        return null;
    }

    /**
     * 读取请求的参数
     * @param uri
     * @return
     */
    private String[] parse_qsparams(String uri){

        String[] is_qsparma=uri.split("\\?");
        if(is_qsparma.length>1){
            String[] qsparams=is_qsparma[1].split("&");
            return qsparams;
        }
        return null;
    }

    private  String[] parse_formdata(String requestString){
       String[] is_formdata=requestString.split("Content-Disposition: form-data; name=\"");
       if(is_formdata.length>1){
           String []formdata = new String[is_formdata.length-1];
           for(int i=1;i<is_formdata.length;i++){
              formdata[i-1]=is_formdata[i].split("----------------------------")[0].replace('\"','=').replaceAll("\\s*", "");
           }
           return formdata;
       }
       return null;
    }
    private  String[] parse_params(String[] parse_qsparams,String[] parse_formdata){
        int index1=0,index2=0;
        if(parse_qsparams!=null){
            index1=parse_qsparams.length;
        }
        if(parse_formdata!=null){
            index2=parse_formdata.length;
        }
        String[] params=new String[index1+index2];
        for(int i=0;i<index1;i++){
            params[i]=parse_qsparams[i];
        }
        for(int i=0;i<index2;i++){
            params[index1+i]=parse_formdata[i];
        }
        return params;
    }

    /**
     * 解析请求的header
     */
    private  String parse_header(String requestString){
        String[] is_header = requestString.split("\n");
        String header = "";
        for(int i=0;i<is_header.length;i++){
            if (Character.isLowerCase(is_header[i].charAt(0))){
                header+="\""+is_header[i].trim()+"\",";
            }
        }
        if(header!="") return header;
      return null;
    }

    /**
     * 解析请求的raw
     */
    private String parse_raw(String requestString){
        int index1, index2;
        index1 = requestString.indexOf('{');
        if (index1 != -1) {
            index2 = requestString.indexOf('}', index1 + 1);
            if (index2 > index1)
                return requestString.substring(index1 + 1, index2);
        }
        return null;
    }

    /**
     * 解析请求的binary
     */

    private byte[] parse_binary(String requestString){
        int index1;
        index1 = requestString.indexOf("\n\r");
        if(index1 + 1<requestString.length()){
            try{

                return requestString.substring(index1 + 1, requestString.length()-1).getBytes("UTF-8");
            }catch (Exception ex){
                ex.printStackTrace();
            }

        }
        return null;
    }
    private int parse_index(String requestString){
        int n=requestString.indexOf("\r\n\r\n");
        System.out.println("parse_index:"+n);
        if(n>0) {return n+4;}
        return 0;
    }


}